﻿/**
 * @fileOverview 对话框控制脚本
 * @copyright (c) 2012 (condenast.com.cn)
 * @author jianjun.wang@condenast.com.cn
 * @version 1.0
 * @depend jquery.js mask.js
 */
 
if(typeof CNC=="undefined" || !CNC){
	var CNC = {};
} 

if(typeof CNC.ui=="undefined" || !CNC.ui){
	CNC.ui = {};
} 

(function($){
	/**
	 * @class 对话框控制
	 * @name CNC.ui.DialogControl
	 */
	CNC.ui.DialogControl = function(config){
		this.config = {
			dialog: null,
			closeBtn: null,
			trigger: null,
			position: "fixed",
			offsetTop: null,
			hasMask: true,
			zIndex: 9999,
			maskOpacity: 0.3,
			maskColor: "#000",
			onShow: null,
			onClose: null
		}
		this.isIE6 = navigator.appVersion.indexOf("MSIE 6.0") != -1;

		$.extend(this.config, config);
		this.init();
	}
	CNC.ui.DialogControl.prototype={
		init: function(){
			var self = this, cfg = self.config;
			self.dialogDiv = cfg.dialog;
			self.closeBtn = cfg.closeBtn ? cfg.closeBtn : null;
			self.trigger = cfg.trigger ? cfg.trigger : null;

			self.dialogDiv.css({zIndex: cfg.zIndex, position: cfg.position});
			self.bindEvent();
		},
		bindEvent: function(){
			var self = this;
			if(self.closeBtn){
				self.closeBtn.click(function(){
					self.close();
				});
			}
			if(self.trigger){
				self.trigger.click(function(){
					self.show();
				});
			}
			
			$(window).bind("resize", function(){
				self.setPosition();
			});

			if(self.config.position === "fixed" && self.isIE6){
				self.dialogDiv.css("position", "absolute");
				$(window).bind("scroll", function(){
					self.setPosition();
				});
			}
		},
		show:function(){
			var self = this;
			if(self.config.hasMask){
				self.mask = new CNC.ui.Mask({
					maskOpacity: self.config.maskOpacity,
					maskColor: self.config.maskColor
				});
				self.mask.show();
			}
			self.setPosition();
			self.dialogDiv.show();

			if(self.config.onShow){
				self.config.onShow();
			}
		}, 
		close:function(){
			var self = this;
			self.dialogDiv.hide();	
			if(self.config.hasMask){
				self.mask.close();
			}
			if(self.config.onClose){
				self.config.onClose();
			}
		},
		setPosition:function(){
			var self = this, t, l;
			t = ($(window).height() - self.dialogDiv.outerHeight())/2;
			l = ($(window).width() - self.dialogDiv.outerWidth())/2;

			if(self.isIE6 && self.config.position === "fixed"){
				t = t + $(window).scrollTop();
			}

			if(self.config.offsetTop){
				t = t + self.config.offsetTop;
			}
			self.dialogDiv.css({
				left: l, 
				top: t
			});
		}
	}
})(jQuery);